const path = require('path')
const fs = require('fs')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const AssetsPlugin = require('assets-webpack-plugin')
const autoprefixer = require('autoprefixer')
const cssnano = require('cssnano')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const assetsJsonPath = path.resolve(__dirname, './assets/assets.json')

const isProduction = process.env.NODE_ENV === 'production'
const isDevelopment = process.env.NODE_ENV === 'development'

const webpackConfig = {
  mode: isProduction ? 'production' : 'development',
  entry: {
    bootstrap: path.resolve(__dirname, './src/vendor/bootstrap-sass/index.js'),
    polyfill: path.resolve(__dirname, './src/vendor/polyfill.js'),
    base: path.resolve(__dirname, './src/js/base.js'),
    home: path.resolve(__dirname, './src/js/home.js'),
    resources: path.resolve(__dirname, './src/js/resources.js'),
    'resources-courses': path.resolve(__dirname, './src/js/resources-courses.js'),
    login: path.resolve(__dirname, './src/js/login.js'),
    register: path.resolve(__dirname, './src/js/register.js'),
  },
  output: {
    path: path.resolve(__dirname, 'assets'),
    filename: 'js/[name]' + (
      isProduction
      ? '.[chunkhash:12]'
      : ''
    ) + '.js', 
  },
  devServer: {
    contentBase: path.join(__dirname, '_site'),
    compress: true,
    port: 8080,
    hot: true,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'^/api' : ''}
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, 'src')
        ],
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.(sa|sc|c)ss$/,
        include: [
          path.resolve(__dirname, 'src')
        ],
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: isDevelopment,
            },
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer({
                  overrideBrowserslist: [' > 1%', 'last 2 versions']
                }),
                cssnano
              ]
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: isProduction
            }
          },
        ],
      },
    ]
  },
  resolve: {
    extensions: [
      '.js',
      '.json'
    ],
    alias: {
      environment: path.resolve(__dirname, isProduction
        ? './src/js/environment/production.js'
        : './src/js/environment/development.js'
      ),
      'env-base.scss': path.resolve(__dirname, isProduction
        ? './src/css/base-prod.scss'
        : './src/css/base.scss'
      ),
      'env-bootstrap.scss': path.resolve(__dirname, isProduction
        ? './src/vendor/bootstrap-sass/stylesheets/styles-prod.scss'
        : './src/vendor/bootstrap-sass/stylesheets/styles.scss'
      ),
      
      'env-resources-courses.scss': path.resolve(__dirname, isProduction
        ? './src/css/pages/resources-courses-prod.scss'
        : './src/css/pages/resources-courses.scss'
      ),
      'env-login.scss': path.resolve(__dirname, isProduction
        ? './src/css/pages/login-prod.scss'
        : './src/css/pages/login.scss'
      ),
      'env-register.scss': path.resolve(__dirname, isProduction
        ? './src/css/pages/register-prod.scss'
        : './src/css/pages/register.scss'
      ),
    }
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: 'css/[name]' + (isProduction ? '.[chunkhash:12]' : '') + '.css',
      chunkFilename: '[id].css',
    }),
    new AssetsPlugin({
      filename: 'assets.json',
      path: path.join(__dirname, '_data'),
      fullPath: false,
      processOutput: assets => {
        Object.keys(assets).forEach(bundle => {
          Object.keys(assets[bundle]).forEach(type => {
            let filename = assets[bundle][type]
            assets[bundle][type] = filename.slice(filename.indexOf(bundle))
          })
        })
        
        const outJSON = JSON.stringify(assets, null, 2)
        fs.writeFileSync(assetsJsonPath, outJSON)
        return outJSON
      }
    }),
  ]
}

if (isProduction) {
  webpackConfig.plugins.push(
    new UglifyJsPlugin({
      sourceMap: false,
      uglifyOptions: {
        mangle: true,
      },
    }),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [
        'css/*',
        'js/*'
      ],
      cleanAfterEveryBuildPatterns: []
    }),
  )
}

module.exports = webpackConfig